/*
 * Created on 2005-4-18
 *
 */
package com.hd123.rumba.util;

import java.util.List;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;

/**
 * @author caili
 */
public class ClassifiedHashtable extends Hashtable implements Serializable {
  public static final String ERROR = "error";
  public static final String WARN = "warn";
  public static final String INFO = "info";

  public List getKeysByKeyPrefix(String prefix) {
    List list = new ArrayList();
    Enumeration keys = keys();
    while (keys.hasMoreElements()) {
      String key = (String)keys.nextElement();
      if (key.startsWith(prefix)) {
        list.add(key);
      }
    }
    return list;
  }
  
  public Object putMessage(String key, String type, String message) {
    return super.put(key, new Entry(type, message));
  }

  public String getMessage(String key) {
    Entry e = (Entry) super.get(key);
    if (e != null)
      return e.getMessage();
    else
      return null;
  }

  public String getAllMessages() {
    StringBuffer sb = new StringBuffer();
    Iterator i = createTypedKeyIterator(ERROR);
    while (i.hasNext()) {
      String key = (String) i.next();
      sb.append(getMessage(key) + "\n");
    }
    return sb.toString();
  }
  
  public boolean hasErrorMessage() {
    return createTypedKeyIterator(ERROR).hasNext();
  }

  public Iterator createTypedKeyIterator(String type) {
    ArrayList result = new ArrayList();
    Enumeration keys = this.keys();
    while (keys.hasMoreElements()) {
      String key = (String) keys.nextElement();
      Entry e = (Entry) super.get(key);
      if (e.getType().equals(type)) {
        result.add(key);
      }
    }
    return result.iterator();
  }

  public class Entry {
    private String type;
    private String message;

    public Entry(String type, String message) {
      this.type = type;
      this.message = message;
    }

    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }

    public String getType() {
      return type;
    }

    public void setType(String type) {
      this.type = type;
    }
  }
}
